/**
 * 
 */
package cn.bigcontainer.alt.meta.extension.impl;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Component;

import cn.bigcontainer.alt.common.util.WoKit;
import cn.bigcontainer.alt.meta.dao.MDao;
import cn.bigcontainer.alt.meta.dto.MObjectDto;
import cn.bigcontainer.alt.meta.dto.MViewDto;
import cn.bigcontainer.alt.meta.exception.MException;
import cn.bigcontainer.alt.meta.extension.MKeyCreator;
import cn.bigcontainer.alt.meta.po.MProperty;
import cn.bigcontainer.alt.meta.po.MViewProperty;

/**
 * @author cailei
 * @date 2017年6月20日
 */
@Component(value = MKeyCreator.DEFAULT)
public class MKeyCreatorDefault implements MKeyCreator {

	@Resource
	private MDao woDao;
	
	/*
	 * (non-Javadoc)
	 * 
	 * @see wos.commons.extension.IKeyCreator#create(wos.commons.entities.
	 * MViewDto)
	 */
	@Override
	public void createKeyValues(MViewDto form) {
		List<MViewProperty> formProps = form.getKeyProperties();
		for (MViewProperty fp : formProps) {
			MProperty p = MObjectDto.getProperty(form.getApp().getObject(), fp.getPropertyId());
			if (MProperty.TYPE_VARCHAR.equals(p.getType())) {
				fp.setValue(WoKit.generateKey32());
			} else if (MProperty.TYPE_INTEGER.equals(p.getType()) || MProperty.TYPE_SMALLINT.equals(p.getType())) {
				Object val = woDao.queryMax(form.getApp().getObjectId(), p.getName());
				if (val == null) {
					val = 0;
				} else {
					val = ((Integer)val) + 1;
				}
				fp.setValue(val);
			} else {
				throw new MException(MException.PK_TYPE, p.getId());
			}
		}
	}
}
